package com.easy.facilitaterecycleadapter.adapter;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by Sigthp-P-Department on 2018/5/9.
 */

public class RefreshRecyclerView extends WrapRecyclerView{
    // 下拉刷新的辅助类
    private RefreshViewCreator mRefreshLoaderCreator;
    // 下拉刷新头部的高度
    private int mRefreshViewHeight = 0;
    // 下拉刷新的头部View
    private View mRefreshView;
//    // 手指按下的Y位置
    private int mFingerRefreshDownY;
    // 手指拖拽的阻力指数
    public float mDragIndex = 0.35f;
    // 当前是否正在拖动
    private boolean mCurrentRefreshDrag = false;
    // 当前的状态
    private int mCurrentRefreshStatus;
    // 默认状态
    public int REFRESH_STATUS_NORMAL = 0x0011;
    // 下拉刷新状态
    public int REFRESH_STATUS_PULL_DOWN_REFRESH = 0x0022;
    // 松开刷新状态
    public int REFRESH_STATUS_LOOSEN_REFRESHING = 0x0033;
    // 正在刷新状态
    public int REFRESH_STATUS_REFRESHING = 0x0044;

    private Adapter adapter=null;

    public RefreshRecyclerView(Context context) {
        super(context);
    }

    public RefreshRecyclerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public RefreshRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    //暴露给用户，自定义一个刷新界面
    public void addViewCreator(RefreshViewCreator viewCreator){
        this.mRefreshLoaderCreator =viewCreator;
        addRefreshView();
    }

    @Override
    public void setAdapter(Adapter adapter) {
        super.setAdapter(adapter);
        this.adapter=adapter;
        addRefreshView();
    }

    /**
     * 添加刷新功能
     */
    private void addRefreshView() {
        if(adapter != null && mRefreshLoaderCreator !=null){
            View refreshView = mRefreshLoaderCreator.getRefreshView(getContext(), this);
            if(refreshView!=null){
                addHanderView(refreshView);
                this.mRefreshView=refreshView;
            }
        }else{
            System.out.println("yanjin-----else--mRefreshLoaderCreator--"+mRefreshLoaderCreator);
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()){
            case MotionEvent.ACTION_DOWN:
                //记录手指按下时的Y轴位置
                mFingerRefreshDownY = (int) ev.getRawY();
                break;
            case MotionEvent.ACTION_UP:
                if(mCurrentRefreshDrag){
                    restoreRefreshView();
                }
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 重置
     */
    private void restoreRefreshView(){
        int currentTopMargin = ((MarginLayoutParams) mRefreshView.getLayoutParams()).topMargin;
        int finalTopMargin = -mRefreshViewHeight+1;
        if(mCurrentRefreshStatus == REFRESH_STATUS_LOOSEN_REFRESHING){
            finalTopMargin = 0;
            mCurrentRefreshStatus = REFRESH_STATUS_REFRESHING;
            if(mRefreshLoaderCreator != null){
                mRefreshLoaderCreator.onRefreshing();
            }
            if(mOnRefreshListener != null){
                mOnRefreshListener.onRefresh();
            }
        }
        int distance = currentTopMargin - finalTopMargin;

        //回弹到指定位置
        final ValueAnimator animator=ObjectAnimator.ofFloat(currentTopMargin,finalTopMargin).setDuration(distance);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                float currentTopMargin = (float) animator.getAnimatedValue();
                setRefreshViewMarginTop((int) currentTopMargin);
            }
        });
        animator.start();
        mCurrentRefreshDrag =false;
    }

    /**
     * 刷新Top的距离
     * @param currentTopMargin
     */
    private void setRefreshViewMarginTop(int currentTopMargin) {
        MarginLayoutParams marginLayoutParams = (MarginLayoutParams) mRefreshView.getLayoutParams();
        if(currentTopMargin < -mRefreshViewHeight +1){
            currentTopMargin = -mRefreshViewHeight + 1;
        }
        marginLayoutParams.topMargin = currentTopMargin;
        mRefreshView.setLayoutParams(marginLayoutParams);
    }

    @Override
    public boolean onTouchEvent(MotionEvent e) {
        switch (e.getAction()){
            case MotionEvent.ACTION_MOVE:
                if(canScrollUp() || mCurrentRefreshStatus == REFRESH_STATUS_REFRESHING){
                    return super.onTouchEvent(e);
                }

                //解决下拉刷新自动滚动问题
                if(mCurrentRefreshDrag){
                    scrollToPosition(0);
                }

                int refershDistanceY = (int) ((e.getRawY()-mFingerRefreshDownY) * mDragIndex);
                if(refershDistanceY > 0){
                    int marginTop = refershDistanceY -mRefreshViewHeight;
                    setRefreshViewMarginTop(marginTop);
                    updateRefreshStatus(marginTop);
                    mCurrentRefreshDrag = true;
                    return false;
                }
                break;
        }
        return super.onTouchEvent(e);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if (changed) {
            if (mRefreshView != null && mRefreshViewHeight <= 0) {
                // 获取头部刷新View的高度
                mRefreshViewHeight = mRefreshView.getMeasuredHeight();
                if (mRefreshViewHeight > 0) {
                    // 隐藏头部刷新的View marginTop 多留出1px防止无法判断是不是滚动到头部问题
                    setRefreshViewMarginTop(-mRefreshViewHeight + 1);
                }
            }
        }
    }

    /**
     * 停止刷新
     */
    public void onStopRefresh() {
        mCurrentRefreshStatus = REFRESH_STATUS_NORMAL;
        restoreRefreshView();
        if (mRefreshLoaderCreator != null) {
            mRefreshLoaderCreator.onStopRefresh();
        }
    }

    /**
     * 判断是不是滚动到最顶部，copy源码
     * @return
     */
    private boolean canScrollUp() {
        if(Build.VERSION.SDK_INT < 14){
            return ViewCompat.canScrollVertically(this, -1) || this.getScrollY() > 0;
        }else{
            return ViewCompat.canScrollVertically(this, -1);
        }
    }


    /**
     * 更新状态
     * @param marginTop
     */
    private void updateRefreshStatus(int marginTop) {
        if(marginTop <= -mRefreshViewHeight){
            mCurrentRefreshStatus = REFRESH_STATUS_NORMAL;
        }else if(marginTop < 0){
            mCurrentRefreshStatus = REFRESH_STATUS_PULL_DOWN_REFRESH;
        }else{
            mCurrentRefreshStatus = REFRESH_STATUS_LOOSEN_REFRESHING;
        }
        if(mRefreshLoaderCreator != null){
            mRefreshLoaderCreator.onPullRefersh(marginTop,mRefreshViewHeight,mCurrentRefreshStatus);
        }
    }

    //设置刷新监听
    private OnRefreshListener mOnRefreshListener;
    public void setOnRefreshListener(OnRefreshListener onRefreshListener) {
        this.mOnRefreshListener = onRefreshListener;
    }


    // 处理加载更多回调监听
    private OnLoadMoreListener mOnLoadMoreListener;
    public void setOnLoadMoreListener(OnLoadMoreListener listener) {
        this.mOnLoadMoreListener = listener;
    }

}
